/**
 * Created by henian.xu on 2018/11/9.
 *
 */

module.exports = (options, app) => {
    return async (ctx, next) => {
        await next();
        const { req, res, path: currentPath } = ctx;
        if (app.router.stack.some(item => currentPath === item.path)) return;

        ctx.status = 200;

        if (/\.js$/.test(currentPath)) {
            ctx.set('Content-Type', 'application/javascript');
        }
        if (/\.css/.test(currentPath)) {
            ctx.set('Content-Type', 'text/css');
        }
        // webpack hot reload
        // egg will set 'content-length' with value, it will disable the hot middleware keep alive.
        // egg 默认设置了 'content-length' 值，导致热更新失败，建议去掉该值保持活跃
        if (ctx.path === '/__webpack_hmr') {
            ctx.response.remove('content-length');
        }
        // console.log('nuxtRender', 1);
        return new Promise(resolve => {
            res.on('close', resolve);
            res.on('finish', resolve);
            // the "nuxt.render" returns callback, not Promise
            app.nuxt.render(req, res, () => {
                // console.log('nuxtRender', 2);
                resolve();
            });
        });
    };
};
